package com.example.easytts.security

import jakarta.servlet.FilterChain
import jakarta.servlet.ServletException
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.User
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
import org.springframework.web.filter.OncePerRequestFilter
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.slf4j.LoggerFactory

class JwtAuthFilter : OncePerRequestFilter() {
    private val logger = LoggerFactory.getLogger(JwtAuthFilter::class.java)
    
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        try {
            val authHeader = request.getHeader("Authorization")
            logger.info("Processing request: ${request.requestURI}, Auth header: ${authHeader?.take(20)}...")
            
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                val token = authHeader.substring(7)
                val username = JwtUtil.getUsername(token)
                val roles = JwtUtil.getRoles(token)
                
                logger.info("JWT parsed - Username: $username, Roles: $roles")
                
                if (username != null && SecurityContextHolder.getContext().authentication == null) {
                    val authorities = roles.map { SimpleGrantedAuthority("ROLE_" + it.uppercase()) }
                    val userDetails = User(username, "", authorities)
                    val auth = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)
                    auth.details = WebAuthenticationDetailsSource().buildDetails(request)
                    SecurityContextHolder.getContext().authentication = auth
                    
                    logger.info("Authentication set for user: $username with authorities: $authorities")
                }
            } else {
                logger.warn("No valid Authorization header found")
            }
        } catch (e: Exception) {
            logger.error("Error in JWT filter: ${e.message}", e)
        }
        
        filterChain.doFilter(request, response)
    }
} 